#!/usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
import re
from cupblog.config.server import STR_NAME, STR_ADMINS
from cupblog.db import connect_account_database, connect_database, ensure_index_of_blog
from cupblog.page import getInfoHttpResponse, go_redirect
from func import *

__author__ = 'lihaoquan'

def hello(request):
    return HttpResponse("Hello Cupblog!")

def query_mine_type(ext):
    """
    获取文件的mine格式
    :param ext:
    :return:
    """
    d = {
        'css': 'text/css',
        'js': 'application/x-javascript',
        'png': 'image/png',
        'jpg': 'image/jpeg',
        'gif': 'image/gif',
        'xml': 'text/xml',
        'swf': 'application/x-shockwave-flash',
        'html': 'text/html',
    }

    if ext in d:
        return d[ext]

    return ''

def get_file(request, ext):
    """
    获取静态文件
    """
    path = request.path
    abspath = os.path.abspath('.') + '/' + 'cupblog' + path
    if os.sep != '/':
        abspath = abspath.replace('/', '\\')
    stream = open(abspath, 'rb').read()
    mine = query_mine_type(ext)
    return HttpResponse(stream, mimetype=mine)



#博客首页
def show_homepage(request, page):
    return getInfoHttpResponse(request, 'index.html', {
        'page': u'首页',
        'articles': None,
        'links': None,
        'categories': None,
        'paginator': {
            'Current': page,
            'Total': 1,
            'PerPage': 10
        }
    })


@csrf_exempt
def install(request):
    blog = get_current_blog(request)
    if blog is None:
        return HttpResponse('安装前请配置server.py')

    name = blog[STR_NAME]
    if not re.match(r'^\w+$', name):
       return HttpResponse(
            '博客名称"%s"不合法。规范的名称仅限字母、数字和下划线' % name
        )

    admin = blog[STR_ADMINS]
    if isinstance(admin,list):
        admin = admin[0]
    if not re.match(r'^\w+$', admin):
        return HttpResponse(
            '管理员名称"%s"不合法。规范的名称仅限字母、数字和下划线' % admin
        )

    #接到用户数据库
    db = connect_account_database(request)
    user = db.users.find_one({'Username':admin})
    if user is None:
        return go_redirect(request, '需要创建管理员账户', 'register/?redirect=install')

    if request.method == 'GET':

        admins = blog[STR_ADMINS]
        if isinstance(admin,list):
            admins = ', '.join(admins)

        set_template_dir('admin')
        return render_to_response('install.html', {
            'host':request.get_host(),
            'name': blog[STR_NAME],
            'admins': admins,
        })

    elif request.method == 'POST':
        d = request.POST
        if d.get('is-blog-info-checked') is None:
            return go_redirect(request, '未勾选确认按钮', 'install/')

        db = connect_database(request)
        db.categories.insert({
            'Title': '默认分类',
            'Description': '',
            'Order': 0
        })
        db.infos.insert({
            'TopId': 0,
            'Title': 'RealBlog',
            'Subtitle': 'A blog based of Django and MongoDB',
            'Description': 'No description',
            'Theme': 'default',
            'DefaultTimezone': 'Asia/Shanghai',
            'DefaultTimezoneOffset': '+8',
            'ArticlesPerPage' : 10,
            'CustomRss': '',
            'WeiboCode': '',
            'CommentCode': '',
            'LatestCommentsCode': '',
            'StatisticsCode': '',
            'StatisticsCodeInHead': False,
        })
        #建立索引
        ensure_index_of_blog(db)
        db.connection.disconnect()
        return go_redirect(request, '安装完成', '')


#用户注册
@csrf_exempt
def register(request):
    if request.method == 'GET':

        set_template_dir('admin')
        d = {}
        # 是否注册第一位管理员
        if request.GET.get('redirect') == 'install':
            # 取出第一位管理员
            blog = get_current_blog(request)
            admin = blog[STR_ADMINS]
            if isinstance(admin, list):
                admin = admin[0]

            d['admin'] = admin
            d['is_to_install'] = True # 标记注册后转到安装界面

        return render_to_response('register.html', d)

    elif request.method == 'POST':

        d = request.POST
        password = d['password']
        password_repeat = d['password-repeat']

        #验两次密码输入是否正确
        if password == password_repeat :

            db = connect_account_database(request)

            #检查用户是否存在
            username = d['username']
            if db.users.find_one({'Username':username}):
                return go_redirect(request, '用户已经存在', 'register/')

            # 检查Email是否已存在
            email = d['email']
            if db.users.find_one({'Email':email}):
                return go_redirect(request, 'Email已存在', 'register/')

            nickname = d['nickname']

             # 对密码进行哈希
            hash = hashlib.sha1()
            hash.update((username+password).encode('utf8'))
            passwordHash = hash.hexdigest()

            db.users.insert({
                'Username': username,
                'Password': passwordHash,
                'Nickname': nickname,
                'Email':email,
            })

            db.connection.disconnect()

            # 是否转到安装界面, 否则返回到本页面
            is_to_install = d['is-to-install'] == 'True'

            return go_redirect(request, '新建用户成功', 'install/' if is_to_install else '')
        else:
            return go_redirect(request,'密码重复')











